export const findComponentUpward = (context, componentName) => {
  let parent = context.$parent;
  let name = parent.$options.name;
  while (parent && (!name || [componentName].indexOf(name) < 0)) {
    parent = parent.$parent;
    parent && (name = parent.$options.name);
  }
  return parent;
};

export const findComponentsUpward = (context, componentName) => {
  const parents = [];
  let parent = context.$parent;
  if (parent) {
    if (componentName === parent.$options.name) {
      parents.push(parent);
    }
    return parents.concat(findComponentUpward(parent, componentName));
  } else {
    return [];
  }
};

export const findComponentDownward = (context, componentName) => {
  const childrens = context.$children;
  let children = null;
  if (childrens.length) {
    for (const child of childrens) {
      const name = child.$options.name;
      if (name === componentName) {
        children = child;
        break;
      } else {
        children = findComponentDownward(child, componentName);
        if (children) break;
      }
    }
  }
  return children;
};

export const findComponentsDownward = (context, componentName) => {
  return context.$children.reduce((components, child) => {
    if (componentName === child.$options.name) components.push(child);
    // debugger;
    const foundChilds = findComponentDownward(child, componentName);
    foundChilds && components.concat(foundChilds);
    return components;
  }, []);
};

export const findBrothersComponents = (
  context,
  componentName,
  except = true
) => {
  let res = context.$parent.$children.filter((item) => {
    return item.$options.name === componentName;
  });
  let index = res.findIndex((item) => item._uid === context._uid);
  if (except) {
    res.splice(index, 1);
  }
  return res;
};
